// 控制请求并发
export const concurRequest = (taskPool, max) => {
  return new Promise(resolve => {
    if (taskPool.length === 0) {
      resolve([])
      return
    }

    const results = []
    let index = 0
    let count = 0

    const request = async () => {
      if (index === taskPool.length) return
      const i = index
      const task = taskPool[index]
      index++
      try {
        results[i] = await task()
      } catch (err) {
        results[i] = err
      } finally {
        count++
        if (count === taskPool.length) {
          resolve(results)
        }
        request()
      }
    }

    const times = Math.min(max, taskPool.length)
    for (let i = 0; i < times; i++) {
      request()
    }
  })
}
